import axios from "axios";
import configSetting from "@/helper/config";
import { message, Modal } from "ant-design-vue";
import store from "@/store";
import router from "@/router";
import helper from "@/helper/helper";
// import dink from 'dinkjs'
// import router from '@/router'

// 创建axios实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: "/" + process.env.VUE_APP_API_PREFIX,
  // timeout
  timeout: 60 * 1000,
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // baseUrl
    // config.baseURL = process.env.VUE_APP_API_URL
    // timeout
    // config.timeout = 60 * 1000
    // heartbeat
    // dink.setStorage('lastRequestTime', dink.now())
    // header
    // config.headers.Encrypt = configLocal.encrypt.enable
    // if (helper.storage.get('token')) {
    //   Object.assign(config.headers, { 'X-Access-Token': helper.storage.get('token') })
    // }
    // return config

    const token = helper.getToken();
    // 设置请求头
    // if (token && (configSetting.systemType === 'sso' || configSetting.systemType === 'default')) config.headers.token = token
    if (token && configSetting.systemType === "sso")
      config.headers.token = token;
    if (
      (token && configSetting.systemType === "business") ||
      configSetting.systemType === "default"
    )
      config.headers.Authorization = token;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

let refreshing = false; // 正在刷新表示，避免重复刷新
let waitQueue = []; // 请求等待队列

// 响应拦截器
request.interceptors.response.use(
  async (response) => {
    const config = response.config;
    const res = response.data;
    // 二进制数据则直接返回
    if (
      response.request.responseType === "blob" ||
      response.request.responseType === "arraybuffer"
    ) {
      return res;
    }
    if (res.code === 401 || res.code === 402) {
      Modal.warning({
        title: "登录过期",
        content: "返回登录页重新登陆",
        onOk() {
          store.dispatch("clearStore").then(() => {
            if (configSetting.systemType === "business") {
              const redirectUri = encodeURIComponent(
                "http://" + window.location.host + "/"
              );
              window.location.href = `${configSetting.ssoUrl}/login?client_id=${configSetting.clientId}&redirect_uri=${redirectUri}`;
            } else {
              router.push({ name: "login" });
            }
          });
        },
      });
      return Promise.reject(new Error("会话已过期，请重新登录"));
    } else if (res.code === 406) {
      if (!refreshing) {
        refreshing = true; // 切换正在刷新标识，其他请求进入请求等待队列
        const params = {
          client_id: configSetting.clientId,
          client_secret: configSetting.clientSecret,
          Refresh_token: store.getters.refresh_token,
          grant_type: "refresh_token",
        };
        store
          .dispatch("getTokenByCode", params)
          .then(() => {
            waitQueue.forEach((callback) => callback()); // 已成功刷新token，队列中的所有请求重试
            waitQueue = [];
            return request(config);
          })
          .catch(() => {})
          .finally(() => {
            refreshing = false;
          });
      } else {
        return new Promise((resolve) => {
          waitQueue.push(() => {
            resolve(request(config));
          });
        });
      }
    } else if (res.code !== 200) {
      // message.error(res.msg);
      // return Promise.reject(new Error(res.msg));
    }
    return res;
  },
  (error) => {
    if (
      error.response.status === 500 &&
      error.response.data.message === "Token失效，请重新登录"
    ) {
      helper.msg.error("登录超时");
      helper.storage.clear();
      router.push({ name: "login" });
    } else {
      helper.msg.error(error.message);
    }
    let { message: EMessage } = error;
    if (EMessage === "Network Error") {
      EMessage = "后端接口连接异常";
    } else if (EMessage.includes("timeout")) {
      EMessage = "系统接口请求超时";
    } else if (EMessage.includes("Request failed with status code")) {
      EMessage = "系统接口" + EMessage.substr(EMessage.length - 3) + "异常";
    }
    message.error(EMessage);
    return Promise.reject(error);
  }
);

// 通用下载方法
export function download(url, params, filename) {
  return request
    .post(url, params, {
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      responseType: "blob",
    })
    .then(async ({ data, name }) => {
      // { data, name } 可根据后端返回数据结构调整
      const downName = name || filename;
      const blob = new Blob([data]);
      const downloadElement = document.createElement("a");
      const href = window.URL.createObjectURL(blob); // 创建下载的链接
      downloadElement.href = href;
      downloadElement.download = downName; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放掉blob对象
    })
    .catch((r) => {
      console.error(r);
      message.error("下载文件出现错误，请联系管理员！");
    });
}

// const http = (url, data, options = {}) => {
//   // const result = axios({
//   const result = request({
//     url: url,
//     ...options,
//     params: options.method === 'get' ? data : {},
//     data: data
//   })
//   return result
// }

// const dom = (url, data, options = {}) => {
//   options.method = 'get'
//   return http(url, data, options)
// }

// const get = (url, data, options = {}) => {
//   options.method = 'get'
//   return http(url, data, options)
// }

// const post = (url, data, options = {}) => {
//   options.method = 'post'
//   return http(url, data, options)
// }

// const put = (url, data, options = {}) => {
//   options.method = 'put'
//   return http(url, data, options)
// }

// const del = (url, data, options = {}) => {
//   options.method = 'delete'
//   return http(url, data, options)
// }

// const upload = (url, data, options = {}) => {
//   options.method = 'post'
//   return http(url, data, options)
// }

// export default {
//   dom,
//   get,
//   post,
//   put,
//   del,
//   upload
// }

export default request;
